//
//  BleInfoViewController.m
//  MLBleSDK
//
//  Created by 程杰 on 2023/10/20.
//

#import "BleInfoViewController.h"
#import "Masonry.h"

#import <SystemConfiguration/CaptiveNetwork.h>
@interface BleInfoViewController ()
@property(nonatomic, strong) NSString *wifiName;
@property (nonatomic, strong) UITextField *wifiNameField;
@property (nonatomic, strong) UITextField *passwordField;
@property (nonatomic, strong) UITextField *sendContentField;
@property (nonatomic, strong) UIButton *networkButton;
@property (nonatomic, strong) UIButton *sendButton;
@property (nonatomic, strong) UILabel *resultLabel;
@property(nonatomic, strong) UIButton *getDeviceInfoButton;

@end
@implementation BleInfoViewController

-(NSDictionary*)getWifiInfo{
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    
    if (!wifiInterfaces) {
        return nil;
    }
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);
            
            return networkInfo;
        }
    }
    
    return nil;
}

- (void)viewDidAppear:(BOOL)animated {
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
- (void)viewDidDisappear:(BOOL)animated {
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    if (self.isMovingFromParentViewController) { // 判断页面是否是通过返回按钮被移除的
        NSLog(@"返回按钮被点击了");
        [[MLBLEManager sharedManager] disconnectFromPeripheral:self.model.peripheral];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 如果配网这里需要wifi名称和密码
    self.wifiName = [self getWifiInfo][@"SSID"] ?: @"Tenda_aa";
    self.wifiNameField.text = self.wifiName;
    self.passwordField.text = @"123456";

    // 测试方便，可自行填写，16进制字符串内容
    self.sendContentField.text = @"FF";//
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view becomeFirstResponder];
    [self setupUI];
    
    
    [self ml_ListenReceiveData];
    
    // 设备断开监听
    [[MLBLEManager sharedManager] listenBleDisConnect:^(BOOL success, CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
        if (success) {
            [SVProgressHUD showInfoWithStatus:@"设备已断开，请返回重新连接"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}

/// 监听数据
- (void)ml_ListenReceiveData {
    /// 监听数据
    [[MLBLEManager sharedManager] listenBleReceiveDataResult:^(MLBleResultInfos * _Nonnull infos) {
       
        if (infos.code == 200) {
            self.resultLabel.text = [NSString stringWithFormat:@"接受到的消息16进制格式为:\n%@",infos.receiveData];
            NSLog(@"接收到2：%@",infos.receiveData);
        }
    }];
}

/// 发送数据
- (void)sendButtonClick:(id)sender {
    if (self.model.peripheral == nil) {
        [SVProgressHUD showErrorWithStatus:@"请先连接设备"];
        return;
    }   

    NSString *hexPattern = @"^[0-9A-Fa-f]+$";
    NSPredicate *hexPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", hexPattern];
    if (self.sendContentField.text.length == 0 || ![hexPredicate evaluateWithObject:self.sendContentField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入16进制数据"];
        return;
    }

    MLBleParamsItem *item = [MLBleParamsItem new];
    item.codeType = ML_SEND_CODE_TYPE;
    item.bleModel = self.model;
    item.sendData = self.sendContentField.text;
    [[MLBLEManager sharedManager] setParamsInfo:item result:^(MLBleResultInfos * _Nonnull infos) {
        
      if (infos.code == 200) {
       
          // 此处也可以监听，但是需要初始化。
          if (infos.receiveData) { // 回调接收到的
              NSLog(@"接收到1：%@",infos.receiveData);
              self.resultLabel.text = infos.receiveData;
          } else {
              [SVProgressHUD showSuccessWithStatus:@"发送成功"];
              self.resultLabel.text = @"发送成功";
          }
      } else {
        [SVProgressHUD showErrorWithStatus:infos.message];
        self.resultLabel.text = infos.message;
      }
    }];
}


/// 配网-纯蓝牙
- (void)getDeviceInfoButtonClick:(UIButton *)btn {
    NSLog(@"获取设备信息按钮被点击");
    // 在这里添加获取设备信息的逻辑
    if (self.model.peripheral == nil) {
        [SVProgressHUD showErrorWithStatus:@"请先连接设备"];
        return;
    }
    
    [SVProgressHUD show];
    
    MLBleParamsItem *item = [MLBleParamsItem new];
    item.codeType = ML_BLE_CONFIG_CODE_TYPE; // 获取mac
    item.bleModel = self.model;
    [[MLBLEManager sharedManager] setParamsInfo:item result:^(MLBleResultInfos * _Nonnull infos) {
       
        if (infos.code == 200) {
            [SVProgressHUD showSuccessWithStatus:infos.message];
            self.resultLabel.text = infos.deviceName;
        } else {
            if (infos.message.length > 0) {
                [SVProgressHUD showInfoWithStatus:infos.message];
                self.resultLabel.text = infos.message;
            }
        }
    }];
}


// ap配网方法是
//- (void)networkButtonClick:(UIButton *)btn {
//    
//    NSLog(@"按钮被点击");
//
//    if (self.model.peripheral == nil) {
//        [SVProgressHUD showErrorWithStatus:@"请先连接设备"];
//        return;
//    }
//
//    if (self.wifiNameField.text.length == 0) {
//        [SVProgressHUD showErrorWithStatus:@"请输入WiFi名称"];
//        return;
//    }
//
//    if (self.passwordField.text.length == 0) {
//        [SVProgressHUD showErrorWithStatus:@"请输入WiFi密码"];
//        return;
//    }
//    
//    [SVProgressHUD show];
//    
//    MLBleParamsItem *item = [MLBleParamsItem new];
//    item.codeType = ML_AP_CODE_TYPE; // 获取mac
//    item.wifiName = self.wifiNameField.text;
//    item.wifiPassWorld = self.passwordField.text;
//    item.overTime = 60;// 可选
//    item.bleModel = self.model;
//    [[MLBLEManager sharedManager] setParamsInfo:item result:^(MLBleResultInfos * _Nonnull infos) {
//       
//        if (infos.code == 200) {
//            [SVProgressHUD showSuccessWithStatus:@"配网成功"];
//            
//            MLBLEModel *model = infos.bleModel;
//            NSString *showInfo = [NSString stringWithFormat:@"配网成功：\ntype:7\nmac:%@\nkind:%@\nmodel:%@\n<==>:%@",
//                                  model.mac,model.mlModel,model.mlKind,model.name];
//            NSLog(@"MLBLEConnectStateSuccess result:%@",showInfo);
//            self.resultLabel.text = showInfo;
//        } else {
//            if (infos.message.length > 0) {
//                [SVProgressHUD showInfoWithStatus:infos.message];
//                self.resultLabel.text = infos.message;
//            }
//        }
//    }];
//}

- (void)setupUI {
    [self.wifiNameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(100);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(40);
    }];
    
    [self.passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.wifiNameField.mas_bottom).offset(10);
        make.left.right.height.equalTo(self.wifiNameField);
    }];
    
    [self.sendContentField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordField.mas_bottom).offset(10);
        make.left.right.height.equalTo(self.wifiNameField);
    }];
    
//    [self.networkButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.sendContentField.mas_bottom).offset(50);
//        make.left.equalTo(self.view).offset(20);
//        make.right.equalTo(self.view).offset(-20);
//        make.height.mas_equalTo(44);
//    }];
    
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.sendContentField.mas_bottom).offset(50);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(44);
    }];
    
    // 添加配网
    [self.getDeviceInfoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.sendButton.mas_bottom).offset(50);
        make.left.right.height.equalTo(self.sendButton);
    }];
    
    [self.resultLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.getDeviceInfoButton.mas_bottom).offset(20);
        make.left.right.equalTo(self.sendButton);
    }];
}

#pragma mark - Lazy Loading

- (UITextField *)wifiNameField {
    if (!_wifiNameField) {
        _wifiNameField = [[UITextField alloc] init];
        _wifiNameField.placeholder = @"输入WiFi名称";
        _wifiNameField.borderStyle = UITextBorderStyleRoundedRect;
        [self.view addSubview:_wifiNameField];
    }
    return _wifiNameField;
}

- (UITextField *)passwordField {
    if (!_passwordField) {
        _passwordField = [[UITextField alloc] init];
        _passwordField.placeholder = @"输入密码";
        _passwordField.borderStyle = UITextBorderStyleRoundedRect;
//        _passwordField.secureTextEntry = YES;
        [self.view addSubview:_passwordField];
    }
    return _passwordField;
}

- (UITextField *)sendContentField {
    if (!_sendContentField) {
        _sendContentField = [[UITextField alloc] init];
        _sendContentField.placeholder = @"输入发送内容-格式为16进制";
        _sendContentField.borderStyle = UITextBorderStyleRoundedRect;
        [self.view addSubview:_sendContentField];
    }
    return _sendContentField;
}

- (UIButton *)networkButton {
    if (!_networkButton) {
        _networkButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_networkButton setTitle:@"ap配网" forState:UIControlStateNormal];
        [_networkButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _networkButton.backgroundColor = [UIColor blueColor];
        [_networkButton addTarget:self action:@selector(networkButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_networkButton];
    }
    return _networkButton;
}

- (UIButton *)sendButton {
    if (!_sendButton) {
        _sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sendButton setTitle:@"发送内容" forState:UIControlStateNormal];
        [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _sendButton.backgroundColor = [UIColor blueColor];
        [_sendButton addTarget:self action:@selector(sendButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_sendButton];
    }
    return _sendButton;
}

- (UILabel *)resultLabel {
    if (!_resultLabel) {
        _resultLabel = [[UILabel alloc] init];
        _resultLabel.numberOfLines = 0;
        _resultLabel.textColor = [UIColor blackColor];
        [self.view addSubview:_resultLabel];
    }
    return _resultLabel;
}

- (UIButton *)getDeviceInfoButton {
    if (!_getDeviceInfoButton) {
        _getDeviceInfoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_getDeviceInfoButton setTitle:@"纯蓝牙配网" forState:UIControlStateNormal];
        [_getDeviceInfoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _getDeviceInfoButton.backgroundColor = [UIColor blueColor];
        [_getDeviceInfoButton addTarget:self action:@selector(getDeviceInfoButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_getDeviceInfoButton];
    }
    return _getDeviceInfoButton;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
